package com.example.demo.算法_test.graph;

import java.util.HashSet;
import java.util.List;
import java.util.Stack;

/**
 * @program: java_base
 * @description: 图结构，深度优先遍历
 * @author: zhouhongtao
 * @happyCreateTime: 2022/03/15 09:20
 */
public class DFSGraph {

    class Node {
        int value;
        List<Node> neighbors;
    }

    /**
     * 深度优先遍历
     * 使用栈，和防重结构
     * @param node
     */
    public void dfs(Node node){
        if (node==null){
            return;
        }
        Stack<Node> stack = new Stack<>();
        HashSet set = new HashSet();
        stack.push(node);
        set.add(node);
        System.out.println(node.value);

        while (!stack.isEmpty()){
            Node cur = stack.pop();
            List<Node> neighbors = cur.neighbors;
            for (Node next : neighbors){
                if (!set.contains(next)){
                    stack.push(cur);
                    stack.push(next);
                    set.add(next);
                    System.out.println(next.value);
                    break;
                }
            }
        }
    }
}
